package cn.org.donald.framework.handler;

import cn.org.donald.framework.constant.TableConstant;
import cn.org.donald.framework.pojo.dto.RequestInfo;
import cn.org.donald.framework.util.RequestUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import java.util.Date;

/**
 * sql自动注入
 * @author ： Donald
 * @since ： 2020/10/24 23:00
 */
@Configuration
public class MybatisPlusHandler implements MetaObjectHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final Date DATE = new Date();

    @Autowired
    private RequestInfo requestInfo;

    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("filling in field: {}","insert");
        fillCreate(metaObject);
        fillModify(metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("filling in field: {}","update");
        fillModify(metaObject);
    }

    private void fillModify(MetaObject metaObject){
        // 修改人id
        this.setFieldValByName(TableConstant.FIELD_MODIFIED_BY,getUserId(),metaObject);
        // 修改人名称
        this.setFieldValByName(TableConstant.FIELD_MODIFIER,getUserName(),metaObject);
        // 修改时间
        this.setFieldValByName(TableConstant.FIELD_GMT_MODIFIED,new Date(),metaObject);
    }

    private void fillCreate(MetaObject metaObject){
        // 创建人id
        this.setFieldValByName(TableConstant.FIELD_CREATED_BY,getUserId(),metaObject);
        // 创建人名称
        this.setFieldValByName(TableConstant.FIELD_CREATOR,getUserName(),metaObject);
        // 创建时间
        this.setFieldValByName(TableConstant.FIELD_GMT_CREATED,new Date(),metaObject);
    }

    /**
     * 获取userId
     * @return userId
     */
    private Long getUserId(){
        Long userId = null;
        try {
            userId = requestInfo.getUserId();
            logger.info("get userId from requestInfo");
        }catch (Exception e){
            logger.info("userId is null");
        }
        return userId == null?TableConstant.VALUE_ADMIN_USER_ID:userId;
    }

    /**
     * 获取userName
     * @return userName
     */
    private String getUserName(){
        String userName = null;
        try {
            userName = RequestUtil.getUserNameByAuthorization(requestInfo.getAuthorization());
            logger.info("get userName from requestInfo");
        }catch (Exception e){
            logger.info("userName is null");
        }
        return userName == null?TableConstant.VALUE_ADMIN_USER_NAME:userName;
    }
}
